package models

import (
	"os"
	"strings"

	"gorm.io/gorm"
)

type User struct {
	ID          int      `json:"id"`
	Openid      string   `json:"-" gorm:"column:openid;"`
	Name        string   `json:"name" gorm:"column:name;" validate:"min=1"`
	Avatar      string   `json:"avatar" gorm:"column:avatar;" validate:"-"`
	Phone       string   `json:"phone" gorm:"column:phone;" validate:"-"`
	Gender      int      `json:"gender" gorm:"column:gender;" validate:"gte=0,lte=2"`
	Age         int      `json:"age" gorm:"column:age;" validate:"gte=1,lte=120"`
	Professtion int      `json:"professtion" gorm:"column:professtion;" validate:"gte=0,lte=10"`
	LastLoginAt JSONTime `json:"-" gorm:"column:last_login_at;->;<-"`
	CreatedAt   JSONTime `json:"created_at" gorm:"column:created_at;->;"`
}

func (u *User) AfterFind(tx *gorm.DB) (err error) {
	if u.Avatar != "" {
		u.Avatar = os.Getenv("STATIC_RESOURCE_URL") + u.Avatar
	} else {
		u.Avatar = os.Getenv("STATIC_RESOURCE_URL") + "images/default_avatar.jpg"
	}
	return
}

func (u *User) BeforeUpdate(tx *gorm.DB) (err error) {
	if strings.HasPrefix(u.Avatar, os.Getenv("STATIC_RESOURCE_URL")) {
		u.Avatar = u.Avatar[len(os.Getenv("STATIC_RESOURCE_URL")):]
	}
	return
}
